package cn.com.twoke.easyproject.aspect.request.lock.hook.after;

import cn.com.twoke.easyproject.aspect.request.lock.RequestLock;
import cn.com.twoke.easyproject.aspect.request.lock.RequestLockKeyGenerator;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;

import java.util.ArrayList;
import java.util.List;

/**
 * 请求锁生成装饰器，包装请求锁生成器，添加一些额外的后置操作，包括但不限于，添加请求地址、用户信息以及压缩
 */
@Slf4j
public class RequestLockKeyGenerateAfterDecorator implements RequestLockKeyGenerator {

    private final List<GenerateKeyHook> POOLS = new ArrayList<>();
    private final RequestLockKeyGenerator requestLockKeyGenerator;

    public RequestLockKeyGenerateAfterDecorator(RequestLockKeyGenerator requestLockKeyGenerator) {
        this.requestLockKeyGenerator = requestLockKeyGenerator;
    }

    public RequestLockKeyGenerateAfterDecorator add(GenerateKeyHook handler) {
        POOLS.add(handler);
        return this;
    }

    @Override
    public String generateKey(ProceedingJoinPoint joinPoint, RequestLock requestLock) {
        String key = this.requestLockKeyGenerator.generateKey(joinPoint, requestLock);
        for (GenerateKeyHook hook : POOLS) {
            log.info("{} 处理前 ===>  {} ", hook.getClass().getName(), key);
            key = hook.doAfter(key, joinPoint, requestLock);
            log.info("{} 处理后 ===>  {} ", hook.getClass().getName(), key);
        }
        log.info("RequestLockKey ===> {}", key);
        return key;
    }
}
